﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using System.Configuration;
using NHibernate.Tool.hbm2ddl;
using NHibernate.Cache;
using NerdDinner.Data.Entities;
using Newtonsoft.Json;
using NHibernate.Linq;
using System.IO;
using System.Runtime.Serialization.Json;

namespace NerdDinner.Data
{
    public class WalkRepository
    {
        public ISession Session
        {
            get { return NHibernateSessionPerRequest.GetCurrentSession(); }
        }

        public void AddWalk(Walk walk)
        {
            Session.Save(walk);
        }
                
        public  IList<Walk> GetWalks()
        {
            var walks = Session.CreateCriteria(typeof(Walk))
            .SetFetchMode("Point", FetchMode.Eager)
            .List<Walk>();
            return walks;
        }

        public IList<WalkCategory> Categories()
        {
            var category = Session.CreateCriteria(typeof(WalkCategory))
            .List<WalkCategory>();
            return category;
        }

        public  string GetWalksJson()
        {
            var walks = Session.CreateCriteria(typeof(Walk))
            .SetFetchMode("Point", FetchMode.Eager)
            .List<Walk>();
            string json;
            using (var stream = new MemoryStream())
            {
                DataContractJsonSerializer serializer =
                   new DataContractJsonSerializer(walks.GetType());
                serializer.WriteObject(stream, walks);
                json = Encoding.UTF8.GetString(stream.ToArray());
                return json;
            }
        }

        public IList<Point> GetPoints()
        {
            var points = Session.CreateCriteria(typeof(Point))
            .List<Point>();
            return points;
        }

        public Walk GetWalk(int id)
        {
            var walk = Session.Linq<Walk>().SingleOrDefault(
                w => w.WalkId == id);
            return walk;
        }
    }
}
